package com.example.downloaddemo;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiewei on 15-2-3.
 */
public class Dao {

	private DBHelper helper;

	public Dao(Context context) {
		helper = new DBHelper(context);
	}

	public ArrayList<BlockInfo> getInfos(String urlstr) {
		ArrayList<BlockInfo> list = new ArrayList<BlockInfo>();
		SQLiteDatabase database = helper.getReadableDatabase();
		String sql = "select thread_id, start_pos, end_pos,complete_size from download_info where url=?";
		Cursor c = database.rawQuery(sql, new String[]{urlstr});
		//c.moveToFirst();
		while (c.moveToNext()) {
			BlockInfo info = new BlockInfo(c.getInt(0), c.getInt(1), c.getInt(2), c.getInt(3), urlstr);
			list.add(info);
		}
		c.close();
		return list;
	}

	public boolean hasInfos(String url) {
		SQLiteDatabase database = helper.getReadableDatabase();
		String sql = "select count(*) from download_info where url= ?";
		Cursor c = database.rawQuery(sql, new String[]{url});
		c.moveToFirst();
		int count = c.getInt(0);
		c.close();
		return count != 0;
	}

	public void updataInfo(int threadId, int completeSize, String urlstr) {
		SQLiteDatabase database = helper.getWritableDatabase();
		String sql = "update download_info set complete_size=? where thread_id=? and url=?";
		database.execSQL(sql, new String[]{completeSize + "", threadId + "", urlstr});
	}

	public void closeDb() {
		helper.close();
	}

	public void saveInfo(ArrayList<BlockInfo> infos) {
		SQLiteDatabase database = helper.getWritableDatabase();
		String sql = "insert into download_info (thread_id,start_pos, end_pos,complete_size,url) values(?,?,?,?,?)";
		for (BlockInfo info : infos) {
			Object[] args = new Object[]{info.getThreadId(), info.getStartPos(), info.getEndPos(), info.getCompeleteSize(), info.getUrl()};
			database.execSQL(sql, args);
		}

	}

	public void deleteInfo(String url) {
		SQLiteDatabase database = helper.getWritableDatabase();
		String sql = "delete from download_info where url=?";
		database.execSQL(sql, new String[]{url});
	}
}
